<?php

App::uses('AppModel', 'Model');

class Finance extends AppModel {
    
    public $name = 'Finance';
    public $useTable = 'finance';
    
    public $validate = array(
        'date'   => array('rule' => 'date', 'message' => STR_REQUIRED_FIELD),
        'entity' => array('rule' => 'notEmpty', 'message' => STR_REQUIRED_FIELD),
        'amount' => array('rule' => 'decimal', 'message' => STR_INVALID_FIELD)
    );
    
    public function getInitState($cycle, $onDate) {
        $data = $this->find('all', array(
            'conditions' => array(
                'date >=' => $cycle['date'],
                'date <' => $onDate
            ),
            'recursive' => false,
            'fields' => array('type', 'SUM(amount) as amount'),
            'group'  => 'type'
        ));
        
        $state = $cycle['amount'];
        foreach ($data as $row) {
            switch ($row['Finance']['type']) {
                case 'income':
                    $state += (float)$row[0]['amount'];
                    break;
                case 'expense':
                    $state -= (float)$row[0]['amount'];
                    break;
            }
        }
        
        return $state;
    }
    
    public function get($start, $end, $type=null) {
        $conditions = array(
            'date >=' => $start,
            'date <=' => $end
        );
        
        if (! empty($type)) {
            $conditions['type'] = $type;
        }
        
        return $this->find('all', array(
            'conditions' => $conditions,
            'order' => 'date'
        ));
    }
}

?>